package com.aiti.lulian.controller;

import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CardBusinessContractDto;
import com.aiti.lulian.dto.CardBusinessContractInsert;
import com.aiti.lulian.entity.CardContractCollaborator;
import com.aiti.lulian.handler.HeaderStyleHandler;
import com.aiti.lulian.service.CardBusinessContractService;
import com.aiti.lulian.service.CardContractCollaboratorService;
import com.aiti.lulian.vo.CardBusinessContractExportVo;
import com.aiti.lulian.vo.CardBusinessContractVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;

/**
 * 合同控制层
 */
@Slf4j
@Api(tags = "合同控制层")
@RestController
@RequestMapping("contract")
public class CardBusinessContractController extends WebController {


    @Autowired
    private CardBusinessContractService cardBusinessContractService;

    @Autowired
    private CardContractCollaboratorService contractCollaboratorService;




    @ApiOperation("新建")
    @PostMapping
    public Message insert(@Validated(CardBusinessContractInsert.class) @RequestBody CardBusinessContractDto dto) {
        if (StringUtils.isEmpty(dto.getBaseCreateBy())) {
            dto.setBaseCreateBy(findUserId());
        }
        return cardBusinessContractService.insertContract(dto);
    }

    @ApiOperation("编辑")
    @PutMapping
    public Message update(@RequestBody CardBusinessContractDto dto) {
        dto.setBaseUpdateBy(findUserId());
        return cardBusinessContractService.updateContract(dto);
    }


    @ApiOperation("根据baseId查询合同详情")
    @GetMapping("/detail")
    public Message queryBoDetailsByBaseId(@RequestParam("baseId") String baseId) {
        return cardBusinessContractService.detailInfo(baseId);
    }

    @ApiOperation("合同列表分页")
    @GetMapping("/page")
    public Message page(CardBusinessContractDto dto) {
        if (StringUtils.isEmpty(dto.getUserId())) {
            dto.setUserId(findUserId());
        }
        Page page = startPage(dto);
        return cardBusinessContractService.getList(page, dto);
    }

    @ApiOperation("删除合同")
    @PostMapping("/delete")
    public Message delete(@RequestBody CardBusinessContractDto dto) {
        List<String> idList = dto.getIdList();
        if(!CollectionUtils.isEmpty(idList)){
            cardBusinessContractService.removeByIds(idList);
            contractCollaboratorService.remove(new LambdaQueryWrapper<CardContractCollaborator>().in(CardContractCollaborator::getRelateId, idList));

        }
        return Message.success();
    }

    @ApiOperation("列表批量编辑")
    @PutMapping("/updateBatch")
    public Message updateBatch(@RequestBody CardBusinessContractDto dto) {
        return cardBusinessContractService.updateListContract(dto);
    }

    @ApiOperation("后台crm列表导入合同")
    @PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Message importExcel(@ModelAttribute CardBusinessContractDto dto) {
        dto.setUserId(findUserId());
        // 确保文件和其他参数已经正确设置到 dto 中
        if (dto.getFile() == null || dto.getFile().isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        return cardBusinessContractService.importExcel(dto);
    }

    @ApiOperation("后台crm列表导出合同")
    @GetMapping("/export")
    public void exportExcel (HttpServletResponse response, CardBusinessContractDto dto) throws Exception {
        // 设置响应头，确保浏览器以下载方式处理文件
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 设置用户 ID
        dto.setUserId(findUserId());

        // 获取合同列表
        List<CardBusinessContractVo> contractList = cardBusinessContractService.getExportList(dto);

        // 检查列表是否为空，如果为空则创建一个空列表
        if (contractList == null || contractList.isEmpty()) {
            contractList = Collections.emptyList();
        }

        // 设置文件名，注意需要对中文进行 URL 编码
        String fileName = URLEncoder.encode("合同导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + fileName + ".xlsx\";" +
                        " filename*=UTF-8''" + fileName + ".xlsx");

        // 使用 EasyExcel 写入数据到输出流
        try (

                OutputStream outputStream = response.getOutputStream()
        ) {

            EasyExcel.write(outputStream, CardBusinessContractExportVo.class)
                    .sheet("合同")
                    .registerWriteHandler(new HeaderStyleHandler())
                    .doWrite(contractList);
        }
    }

    @ApiOperation("新建")
    @PutMapping("/dispatch")
    public Message dispatch(@RequestBody CardBusinessContractDto dto) {
        if(StringUtils.isEmpty(dto.getUserId())){
            dto.setUserId(findUserId());
        }
        return cardBusinessContractService.dispatch(dto);
    }

    @ApiOperation("新建（免校验）")
    @PostMapping("/business")
    public Message insertNonCheck(@RequestBody CardBusinessContractDto dto) {
        if (StringUtils.isEmpty(dto.getBaseCreateBy())) {
            dto.setBaseCreateBy(findUserId());
        }
        return cardBusinessContractService.insertContractNonCheck(dto);
    }


}